/*
 * Copyright (c) 2016 zhangcm. All Rights Reserved.
 */
package com.jnzc.ocr.serv.system.service.impl;

import com.google.gson.reflect.TypeToken;
import com.jnzc.ocr.common.consts.ErrorConsts;
import com.jnzc.ocr.common.error.BusinessException;
import com.jnzc.ocr.common.utils.BusinessUtils;
import com.jnzc.ocr.common.utils.JsonUtils;
import com.jnzc.ocr.common.utils.ValidateUtils;
import com.jnzc.ocr.serv.system.entity.SysDict;
import com.jnzc.ocr.serv.system.mapper.SysDictMapper;
import com.jnzc.ocr.serv.system.service.SysDictService;
import com.jnzc.ocr.serv.system.vo.DictPair;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;

/**
 * @author zhangcm
 * @version 1.0, 2017/9/17
 */
@Service
public class SysDictServiceImpl implements SysDictService {

    @Autowired
    private SysDictMapper sysDictMapper;

    @Override
    public DictPair findPair(String code, Integer pairId) {
        List<DictPair> list = listPair(code);
        for (DictPair obj : list) {
            if(pairId.equals(obj.getId())){
                return obj;
            }
        }
        throw new BusinessException(ErrorConsts.BUSINESS, "字典信息不存在");
    }

    @Override
    public List<DictPair> listPair(String code) {
        SysDict dict = find(code);
        return JsonUtils.fromJson(dict.getValue(), new TypeToken<List<DictPair>>(){}.getType());
    }

    private SysDict find(String code){
        ValidateUtils.notEmpty(code, "字典编码");
        SysDict filter = new SysDict();
        filter.setCode(code);
        SysDict obj = sysDictMapper.selectOne(filter);
        if(null == obj || StringUtils.isEmpty(obj.getValue())){
            BusinessUtils.throwException("字典信息不存在");
        }
        return obj;
    }
}
